<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
include_once APPPATH.'modules/channel/taobao/sdk1311/TopClient.php';
include_once APPPATH.'modules/channel/taobao/sdk1311/request/ItemGetRequest.php';
include_once APPPATH.'modules/channel/taobao/sdk1311/request/ShopGetRequest.php';
class taobao_api{
	private $channel='taobao';
	protected $info;
	protected $client;
	protected $item_get_request;

	function __construct(){
		$settingapi = load_api('setting');
		$settingkey = 'socialapi';
		$socialapis = $settingapi->getSetting($settingkey);
		$apisetting = $socialapis['taobao'];
		$this->info = array(
				'APPKEY'=>$apisetting['appkey'],
				'APPSECRET'=>$apisetting['appsecret'],
				'PROMOTION_ID'=>$apisetting['unionid'],
				'CALLBACK'=>$apisetting['callback'],
		);;
		$this->client = new TopClient();
		$this->client->appkey = $this->info['APPKEY'];
		$this->client->secretKey = $this->info['APPSECRET'];
		//$this->item_get_request = new TaobaokeItemsDetailGetRequest();
		$this->item_get_request = new ItemGetRequest();
	}

	public function fetchurl($url){
		$item_id = $this->get_item_id($url);
		$result = $this->fetch_goodinfo($item_id);
		if(isset($result['orgin_image_url'])){
			$result['type'] = 'channel';
			$result['channel'] = $this->channel;
			$result['item_id'] = $item_id;
			return $result;
		}
		return FALSE;
	}

	/* public function fetch_goodinfo($pid){

	$this->item_get_request->setFields("num_iid,detail_url,title,click_url,price,nick,pic_url,desc,location,shop_click_url,item_img");
	$this->item_get_request->setNumIids($pid);
	$this->item_get_request->setPid($this->info['PROMOTION_ID']);


	$item_resp = $this->client->execute($this->item_get_request);
	if(!isset($item_resp->taobaoke_item_details))
		return false;

	$promotion = (array)$item_resp->taobaoke_item_details->taobaoke_item_detail;
	$item = (array)$item_resp->taobaoke_item_details->taobaoke_item_detail->item;
	$location = (array)$item_resp->taobaoke_item_details->taobaoke_item_detail->item->location;
	$item_imgs = (array)($item_resp->taobaoke_item_details->taobaoke_item_detail->item->item_imgs);
	$imgs = array();
	$single = $item_imgs['item_img'];
	if($single->url){
	$imgs[]=(array)$single;
	}else{
	foreach ($item_imgs['item_img'] as $img_obj){
	$img_arr = (array)$img_obj;
	$img_arr['thumburl'] = $img_arr['url'].'_200x200.jpg';
	$img_arr['imageurl'] = $img_arr['url'];
	$img_arr['url'] = $item['detail_url'];
	$imgs[] = $img_arr;
	}
	}
	$result = array();
	$result['title'] = $item['title'];
	$result['price'] = $item['price'];
	$result['desc'] = $item['title'];
	$result['id'] = $item['num_iid'];
	$result['city'] = $location['city'];
	$result['state'] = $location['state'];
	//$result['item_imgs'] = $this->get_desc_image($item['desc'], $imgs);
	$result['images'] = $imgs;
	$result['orgin_image_url_small'] = $item['pic_url'].'_200x200.jpg';
	$result['orgin_image_url'] = $item['pic_url'];
	$result['url'] = $item['detail_url'];
	$result['shop_name'] = $item['nick'];
	$result['shop_url'] = $promotion['shop_click_url'];
	$result['prourl'] = pzxencode($promotion['click_url']);

	return $result;
	} */

	public function fetch_goodinfo($pid){

		$this->item_get_request->setFields("num_iid,detail_url,title,price,nick,pic_url,desc,location,item_img.url");
		$this->item_get_request->setNumIid($pid);

		$item_resp = $this->client->execute($this->item_get_request);
		if(!isset($item_resp->item))
			return false;

		//$promotion = (array)$item_resp->taobaoke_item_details->taobaoke_item_detail;
		$item = (array)$item_resp->item;
		$location = (array)$item_resp->item->location;
		$item_imgs = (array)($item_resp->item->item_imgs);
		$imgs = array();
		$single = $item_imgs['item_img'];
		if($single->url){
			$img_arr = (array)$single;
			$img_arr['thumburl'] = $img_arr['url'].'_200x200.jpg';
			$img_arr['imageurl'] = $img_arr['url'];
			$img_arr['url'] = $item['detail_url'];
			$imgs[]=$img_arr;
		}else{
			foreach ($item_imgs['item_img'] as $img_obj){
				$img_arr = (array)$img_obj;
				$img_arr['thumburl'] = $img_arr['url'].'_200x200.jpg';
				$img_arr['imageurl'] = $img_arr['url'];
				$img_arr['url'] = $item['detail_url'];
				$imgs[] = $img_arr;
			}
		}
		$result = array();
		$result['title'] = $item['title'];
		$result['price'] = $item['price'];
		$result['desc'] = $item['title'];
		$result['id'] = $pid;
		$result['city'] = $location['city'];
		$result['state'] = $location['state'];
		//$result['item_imgs'] = $this->get_desc_image($item['desc'], $imgs);
		$result['images'] = $imgs;
		$result['orgin_image_url_small'] = $item['pic_url'].'_200x200.jpg';
		$result['orgin_image_url'] = $item['pic_url'];
		$result['url'] = $item['detail_url'];
		$result['shop_name'] = $item['nick'];
		//$result['shop_url'] = $promotion['shop_click_url'];
		//$result['prourl'] = pzxencode($promotion['click_url']);
		//$result['prourl'] = pzxencode($item['detail_url']);
		return $result;
	}

	public function get_desc_image($desc,$images){
		$content = stripslashes($desc);
		$pattern = "/<img[^>]*[^\.][src|file|data-src]\=[\"|\'](([^(>|\"|\')]*)(jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)(\?[^(>|\"|\')]*)?)[\"|\']/iU";

		preg_match_all($pattern, $content, $matches);
		foreach ($matches[1] as $value) {
			if(stripos($value,'http://') === false){
				$parsed_url = parse_url($url);
				$host = isset($parsed_url['host']) ? $parsed_url['host'] : '';
				$port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
				$value = 'http://'.$host.$port.'/'.$value;
			}
			$img['url'] = $value;
			$images[] = $img;
		}
		return $images;
	}

	public function get_promotion_url($itemid){
		if($this->info['PROMOTION_ID'])
		{
			$req = new TaobaokeItemsDetailGetRequest();
			$req->setFields("click_url,shop_click_url");
			$req->setNumIids($itemid);
			$req->setPid($this->info['PROMOTION_ID']);
			$resp = $this->client->execute($req);

			if(isset($resp->taobaoke_item_details))
			{
				$promotion = (array)$resp->taobaoke_item_details->taobaoke_item_detail;
				return $promotion;
				/*
				 * $result['item']['taoke_url'] = $taoke['click_url'];
				* if(!empty($taoke['shop_click_url']))
				 $shop_click_url = $taoke['shop_click_url'];*/
			}
		}
	}

	public function search_gathering($param){
		include_once APPPATH.'modules/channel/taobao/sdk/request/TaobaokeItemsGetRequest.php';

		if($this->info['PROMOTION_ID']){
			$num_per_page = $param['num_per_page']?$param['num_per_page']:10;
			$req = new TaobaokeItemsGetRequest();
			$req->setFields("num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_volume,commission_num,volume");
			$req->setPid($this->info['PROMOTION_ID']);
			$req->setKeyword($param['keyword']);
			$req->setPageNo($param['page']);
			$req->setPageSize($num_per_page);
			$req->setCid($param['channel_category_id']);
				
			$api = load_api('setting');
			$settingkey = 'taobaorule';
			$settings = $api->getSetting($settingkey);
				
			$rule_setting = array('start_price'=>1,'end_price'=>99999,'auto_send'=>'NAN','area'=>'NAN'
					,'start_credit'=>'1heart','end_credit'=>'5goldencrown','sort'=>'commissionRate_desc','guarantee'=>'NAN','start_commissionRate'=>'NAN'
					,'end_commissionRate'=>'NAN','start_commissionNum'=>'NAN','end_commissionNum'=>'NAN','start_totalnum'=>'NAN','end_totalnum'=>'NAN');
				
			if (($startPrice = $settings['start_price'])!='NAN') {
				$req->setStartPrice($startPrice);
			}
			if (($end_price = $settings['end_price'])!='NAN') {
				$req->setEndPrice($end_price);
			}
			if (($auto_send = $settings['auto_send'])!='NAN') {
				$req->setAutoSend(($auto_send)?'true':'false');
			}
			if (($area = $settings['area'])!='NAN') {
				$req->setAutoSend($area);
			}
			if (($start_credit = $settings['start_credit'])!="NAN") {
				$req->setStartCredit($start_credit);
			}
			if (($endCredit = $settings['end_credit'])!="NAN") {
				$req->SetEndCredit($endCredit);
			}
			if ($sort = $settings['sort']) {
				$req->setSort($sort);
			}
			if (($guarantee = $settings['guarantee'])!='NAN') {
				$req->setGuarantee(($guarantee)?'true':'false');
			}
			if (($startCommissionRate = $settings['start_commissionRate'])!='NAN') {
				$req->setStartCommissionRate($startCommissionRate);
			}
			if (($endCommissionRate = $settings['end_commissionRate'])!='NAN') {
				$req->setEndCommissionRate($endCommissionRate);
			}
			if (($startCommissionNum = $settings['start_commissionNum'])!='NAN') {
				$req->setStartCommissionNum($startCommissionNum);
			}
			if (($endCommissionNum = $settings['end_commissionNum'])!='NAN') {
				$req->setEndCommissionNum($endCommissionNum);
			}
			if (($startTotalnum = $settings['start_totalnum'])!='NAN') {
				$req->setStartTotalnum($startTotalnum);
			}
			if (($endTotalnum = $settings['end_totalnum'])!='NAN') {
				$req->setEndTotalnum($endTotalnum);
			}
				
			$this->client->format = 'json';
			$resp = $this->client->execute($req);
				
			$gathering = array();
			$gathering['items'] = $resp->taobaoke_items->taobaoke_item;
			$gathering['total_results'] = $resp->total_results;
			return $gathering;
		}

	}

	public function fetch_categories($parent_id){

		include_once APPPATH.'modules/channel/taobao/sdk/request/ItemcatsGetRequest.php';

		$req = new ItemcatsGetRequest();
		$req->setFields("cid,parent_cid,name,is_parent");
		$req->setParentCid($parent_id);
		$this->client->format = 'json';
		$cats_resp = $this->client->execute($req);
		$categories = $cats_resp->item_cats->item_cat;
		return $categories;

	}

	public function get_item_id($url)
	{
		$url_parse = parse_url($url);
		if(isset($url_parse['query']))
		{
			parse_str($url_parse['query'],$params);
			if(isset($params['id']))
				$item_id = $params['id'];
			elseif(isset($params['item_id']))
			$item_id = $params['item_id'];
		}
		return $item_id;
	}

}
